package com.czxy.changgou3.com.czxy.changgou3.service;

import com.czxy.changgou3.com.czxy.changgou3.mapper.UserMapper;
import com.czxy.changgou3.pojo.User;
import com.czxy.utils.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author zhangmengxiang1@itcast.cn
 * @version 1.0
 * @date 2020/4/21
 */
@Service
@Transactional
public class UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 通过用户名查询
     * @param username
     * @return
     */
    public User findByUsername(String username){
        return this.userMapper.findByUsername(username);
    }

    /**
     * 通过手机号查询
     * @return
     */
    public User findByMobile(String mobile){
        //拼凑条件
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("mobile",mobile);
        //查询
        List<User> users = userMapper.selectByExample(example);
        if (users.size() == 1){
            return users.get(0);
        }
        return null;
    }

    /**
     * 用户注册
     */
    public void register(User user){
        //密码加密
        String hashpw = BCrypt.hashpw(user.getPassword());
        user.setPassword(hashpw);
        //处理数据
        user.setCreatedAt(new Date());
        user.setUpdatedAt(user.getCreatedAt());

        userMapper.insert(user);
    }

}
